#include "user_codec.h"
#include "esp_log.h"
#include "esp_vfs.h"
#include <stdbool.h>
#include <stdio.h>

static const char *TAG = "USER_CODEC";
audio_hal_handle_t s_codec_hal = NULL;

/**
 * @brief Initialize ES8388 codec and I2S driver
 */
esp_err_t user_codec_init(void) {
    // 1. Initialize codec (I2C part + ES8388 register config)
    audio_hal_codec_config_t audio_codec_cfg = AUDIO_CODEC_DEFAULT_CONFIG();
    s_codec_hal = audio_hal_init(&audio_codec_cfg, &AUDIO_CODEC_ES8388_DEFAULT_HANDLE);
    if (!s_codec_hal) {
        ESP_LOGE(TAG, "Failed to initialize audio codec");
        return ESP_FAIL;
    }

    // 2. Start codec in both ADC/DAC mode
    ESP_ERROR_CHECK(audio_hal_ctrl_codec(s_codec_hal, AUDIO_HAL_CODEC_MODE_BOTH, AUDIO_HAL_CTRL_START));

    user_codec_set_volume(100);
    return ESP_OK;
}

/**
 * @brief Set volume (0~100)
 */
esp_err_t user_codec_set_volume(int vol) {
    if (!s_codec_hal)
        return ESP_ERR_INVALID_STATE;
    return audio_hal_set_volume(s_codec_hal, vol);
}

/**
 * @brief Get current volume
 */
esp_err_t user_codec_get_volume(int *vol) {
    if (!s_codec_hal || !vol)
        return ESP_ERR_INVALID_ARG;
    return audio_hal_get_volume(s_codec_hal, vol);
}

/**
 * @brief Deinitialize codec
 */
esp_err_t user_codec_deinit(void) {
    if (!s_codec_hal)
        return ESP_OK;
    audio_hal_deinit(s_codec_hal);
    s_codec_hal = NULL;
    return ESP_OK;
}

void user_set_i2s_clk(int clk, int bits, int ch) {
    if (ch == 1) {
        i2s_stream_set_clk(i2s_reader, clk, bits, 1);
        i2s_stream_set_clk(i2s_writer, clk, bits, 1);
    } else {
        i2s_stream_set_clk(i2s_reader, clk, bits, 1);
        i2s_stream_set_clk(i2s_writer, clk, bits, 2);
    }
}